<?php

/**
 * Class Upload
 */
class Upload extends AppModel {

	/**
	 * Model name
	 *
	 * @type string
	 */
	public $useTable = 'uploads';

	/**
	 * Before save
	 *
	 * @param array $options
	 *
	 * @return bool
	 */
	public function beforeSave($options = []) {
		if (!parent::beforeSave($options)) {
			return false;
		}
		return $this->_processFile();
	}

	/**
	 * Process upload file
	 *
	 * Usually checking against the UPLOAD_ERR_OK constant is enough, but there are other PHP constants available for
	 * finer tuning, which are as follows:
	 * - UPLOAD_ERR_INI_SIZE:
	 * This shows that the uploaded file exceeds the upload_max_filesize directive in your php.ini file
	 * - UPLOAD_ERR_FORM_SIZE:
	 * This shows that the uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
	 * - UPLOAD_ERR_PARTIAL:
	 * This shows that the uploaded file was only partially uploaded
	 * - UPLOAD_ERR_NO_FILE:
	 * This shows that no file was uploaded UPLOAD_ERR_NO_TMP_DIR: This shows that a temporary folder is missing
	 * - UPLOAD_ERR_CANT_WRITE:
	 * This shows that the writing operation to the disk has failed
	 * - UPLOAD_ERR_EXTENSION:
	 * This shows that a PHP extension stopped the file upload
	 *
	 * @return bool
	 */
	public function _processFile() {
		$file = $this->data['Upload']['file'];
		if ($file['error'] === UPLOAD_ERR_OK) {
			$name = md5($file['name']) . strrchr($file['name'], '.');
			$path = WWW_ROOT . 'files' . DS . $name;
			if (is_uploaded_file($file['tmp_name']) && move_uploaded_file($file['tmp_name'], $path)) {
				$this->data['Upload']['name'] = $file['name'];
				$this->data['Upload']['size'] = $file['size'];
				$this->data['Upload']['mime'] = $file['type'];
				$this->data['Upload']['path'] = '/files/' . $name;
				unset($this->data['Upload']['file']);
				return true;
			}
			return false;
		}
	}
}
